//
//  MyStatusViewModel.swift
//  weibo08
//
//  Created by 陈杰明 on 16/3/5.
//  Copyright © 2016年 JM. All rights reserved.
//

import UIKit
import AFNetworking
import SDWebImage

class MyStatusViewModel: NSObject {
    
    func loadSatus(loadStatusCallBack: (status: [MyStatus]?, error: NSError?) -> ()) {
        //网络请求
        MyNetWorkTool.sharedInstance.loadStatus { (result, error) -> () in
            if error != nil {
                MyNetWorkToolError.AccessTokenEmpty.error()
                loadStatusCallBack(status: nil, error: error)
                return
            }
            
            if let array = result?["statuses"] as? [[String : AnyObject]] {
                
                var status = [MyStatus]()
                for dict in array {
                    
                    let statu = MyStatus(dict: dict)
                    
                    status.append(statu)
                    
                }
                self.loadImage(status, loadStatusCallBack: loadStatusCallBack)
                //            print("\n\t模型:\(status)")
                //                loadStatusCallBack(status: status, error: nil)
            }else {
                loadStatusCallBack(status: nil, error: nil)
            }
        }
    }
    
    func loadImage(statuses: [MyStatus], loadStatusCallBack: (status: [MyStatus]?, error: NSError?) -> ()) {
        
        print("bundel:\(NSHomeDirectory())")
        //创建组
        let group = dispatch_group_create()
        
        var length = 0
        
        for status in statuses {
            var urls: [NSURL] = [NSURL]()
            //原创微博
            if let downURL = status.storePictureURL {
                urls = downURL
            }
            //转发微博
            if let downURL = status.retweeted_status?.storePictureURL {
                
                urls = downURL
            }
            //只需要缓存一张图片
            if urls.count == 1 {
                //只下载一张图片
                let url = urls.first
                
                //进入组
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error, _, _, _) -> Void in
                    //离开组
                    dispatch_group_leave(group)
                    if error != nil {
                        print("error:\(error)")
                        return
                    }
                    let data = UIImagePNGRepresentation(image)
                    length += data!.length
                })
            }
        }
        //所有图片加载完成，通知控制器显示数据
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            print("所有图片加载完成，通知控制器显示数据, 缓存图片大小\(CGFloat(length) / 1024 / 1024.0)M")
            loadStatusCallBack(status: statuses, error: nil)
        }
    }
}
